<?php
namespace app\system\controller;
use app\system\controller\SystemController;
/**
 * 百度编辑器配置
 */
class UeditorController extends SystemController {

	/**
     * AJAX上传文件
     */
    public function index(){
        header("Content-Type => text/html; charset=utf-8");
        $action = htmlspecialchars($_GET['action']);
        $config = $this->uploadConfig();
        switch($action){
            //读取配置
            case 'config':
                echo json_encode($config);
                exit;
            //上传文件
            case 'uploadimage':
            case 'uploadvideo':
            case 'uploadfile':
                $result = $this->upload();
                break;
            //远程抓图
            case 'catchimage':
                $result = $this->saveRemote($config);
                break;
            //列出图片
            case 'listimage':
                $result = $this->listFile($config,'img');
                break;
            //列出文件
            case 'listfile':
                $result = $this->listFile($config,'file');
                break;

            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }
        
        /* 输出结果 */
        echo json_encode($result);
    }

    /**
     * 基础配置
     */
    public function uploadConfig(){
        $upSize = config('UPLOAD_SIZE')*1024*1024;
        //获取附件配置
        $systemExts = explode(',', config('UPLOAD_EXTS'));
        $AllowFiles = array();
        foreach ($systemExts as $key => $value) {
            $AllowFiles[] = '.'.$value;
        }
        $imgExt = array(".png", ".jpg", ".jpeg", ".gif", ".bmp");
        $videoExt = array(
                ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid");
        $config = array(
            /* 上传图片配置项 */
            "imageActionName" => "uploadimage",
            "imageFieldName" => "upfile",
            "imageMaxSize" => $upSize,
            "imageAllowFiles" => $imgExt,
            "imageCompressEnable" => false,
            "imageCompressBorder" => 1600,
            "imageInsertAlign" => "none",
            "imageUrlPrefix" => "",
            "imagePathFormat" => "",

            /* 抓取远程图片配置 */
            "catcherLocalDomain" => array("127.0.0.1", "localhost", $_SERVER['SERVER_NAME']),
            "catcherActionName" => "catchimage",
            "catcherFieldName" => "source", 
            "catcherPathFormat" => "",
            "catcherUrlPrefix" => "",
            "catcherMaxSize" => $upSize,
            "catcherAllowFiles" => $imgExt,

            /* 上传视频配置 */
            "videoActionName" => "uploadvideo",
            "videoFieldName" => "upfile",
            "videoPathFormat" => "",
            "videoUrlPrefix" => "",
            "videoMaxSize" => $upSize,
            "videoAllowFiles" => $videoExt,

            /* 上传文件配置 */
            "fileActionName" => "uploadfile",
            "fileFieldName" => "upfile",
            "filePathFormat" => "",
            "fileUrlPrefix" => "",
            "fileMaxSize" => $upSize,
            "fileAllowFiles" => $AllowFiles,

            /* 列出指定目录下的图片 */
            "imageManagerActionName" => "listimage",
            "imageManagerListPath" => "",
            "imageManagerListSize" => 20,
            "imageManagerUrlPrefix" => "",
            "imageManagerInsertAlign" => "none",
            "imageManagerAllowFiles" => $imgExt,

            /* 列出指定目录下的文件 */
            "fileManagerActionName" => "listfile",
            "fileManagerListPath" => "",
            "fileManagerUrlPrefix" => "",
            "fileManagerListSize" => 20,
            "fileManagerAllowFiles" => $AllowFiles,
        );
        return $config;
    }

    /**
     * 列出目录文件
     */
    private function listFile($config,$type){
        $start = request('get.start',0,'intval');
        $size = request('get.size',10,'intval');
        if($type == 'img'){
            $ext = $config['imageManagerAllowFiles'];
        }else{
            $ext = $config['fileManagerAllowFiles'];
        }
        $sql = '';
        foreach ($ext as $value) {
            $sql .= 'OR A.ext = "'.substr($value, 1).'" ';
        }
        $sql = '(' . substr($sql, 2) . ')';
        $where = array();
        $where['A.user_id'] = SYSTEM_ID;
        $where[] = $sql;
        $list = target('SystemFile')->loadList($where, $start.','.$size);
        $fileList = array();
        foreach ($list as $key => $value) {
            $fileList[] = array(
                'url' => $value['url'],
                'time' => $value['time'],
                'title' => $value['title'],
                );
        }
        if(empty($fileList)){
            $result = array(
                "state" => "没有发现上传文件",
                "list" => array(),
                "start" => $start,
                "total" => 0
            );
        }else{
            $result = array(
                "state" => "SUCCESS",
                "list" => $list,
                "start" => $start,
                "total" => count($fileList)
            );
        }
        return $result;
    }

    /**
     * 远程抓图
     */
    private function saveRemote($config){
        $list = array();
        $source = $_POST[$config['catcherFieldName']];
        $dir = UPLOAD_NAME . '/' . date('Y-m-d') . '/';
        $dirPath = BASE_PATH . $dir;
        $urlPath = ROOT_URL . $dir;
        if(!is_dir($dirPath)){
            if(!mkdir($dirPath, 0777, true)){
                return array(
                    'state'=> 'ERROR',
                );
            }
        }
        foreach ($source as $imgUrl) {
            $data = \variant\ext\Http::doGet($imgUrl);
            if(empty($data)){
                continue;
            }
            $ext = strrchr($imgUrl, '.');
            if (!in_array($ext, $config['catcherAllowFiles'])) {
                continue;
            }
            $fileName = basename($imgUrl);
            $title = explode('.', $fileName);
            $title = $title[0];
            $file = $dirPath . $fileName;
            if(is_file($file)){
                $title = $title.'_'.time();
            }
            $saveName = $title . $ext;
            if (!file_put_contents($dirPath . $saveName, $data)) {
                continue;
            }
            $size = strlen($data);
            //保存图片数据
            $data = array();
            $data['url'] = $urlPath . $saveName;
            $data['original'] = $imgUrl;
            $data['title'] = $title;
            $data['ext'] = substr($ext, 1);
            $data['size'] = $size;
            $data['time'] = time();
            $data['user_id'] = SYSTEM_ID;
            if(!target('system/SystemFile')->addData('add', $data)){
                continue;
            }
            //生成返回数据
            $list[] = array(
                'state'=> 'SUCCESS',
                "url" => $urlPath . $saveName,
                "size" => $size,
                "title" => $title,
                "original" => $title,
                "source" => htmlspecialchars($imgUrl)
            );
        }
        return array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        );

    }

    /**
     * 编辑器上传
     */
    public function upload(){
        $file = target('system/SystemFile');
        $info = $file->uploadData();
        if ($info) {
            $return = array(
                "originalName" => $info['title'],
                "name" => $info['title'],
                "url" => $info['url'],
                "size" => $info['size'],
                "type" => '.'.$info['ext'],
                "state" => 'SUCCESS',
            );
        } else {
            $return = array(
                "state" => $file->getError(),
            );
        }
        return $return;
    }
}

